package com.example.demo.config;

import com.example.demo.common.AppConstant;
import com.example.demo.common.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// 登录状态拦截器
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 HttpSession
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(AppConstant.SESSION_USER_KEY) == null) {
//            response.setContentType("text/html;charset=utf8");
//            response.getWriter().write("请先登录!");
//            response.sendRedirect("http://localhost:8080/#/login");
//            response.setContentType("application/json;charset=utf8");
//            response.getWriter().write(new ObjectMapper().writeValueAsString(JsonResult.failure(302,"")));
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
